package com.sailing.lianxi.thread.pattern;

import static org.hamcrest.CoreMatchers.nullValue;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.jar.Attributes.Name;

import javax.print.attribute.ResolutionSyntax;

/**
 * 生产者
 * @author Administrator
 *
 */
public class Producer implements Runnable {

	private String name;
	private CountDownLatch noMoreToProduce;
	private BlockingQueue<Object> queue;
	private Random random = new Random();
	
	public Producer(String name,CountDownLatch noMoreToProduce,BlockingQueue<Object> queue) {
		// TODO Auto-generated constructor stub
		this.name = name;
		this.noMoreToProduce = noMoreToProduce;
		this.queue = queue;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println(name+"----started");
		try {
			while(true) {
				Object item = randomProduce();
				if(item == null) {
					break;
				}
				queue.put(item);
				System.out.println(name+" produced one");
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("异常");
			e.printStackTrace();
		}finally {
			System.out.println(name+" finish");
			noMoreToProduce.countDown();
		}
	}

	private Object randomProduce() {
		if(random.nextBoolean()) {
			return new Object();
		}
		return null;
	}
}
